<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增角色 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="createActions(record)"
          />
        </template>
      </template>
    </BasicTable>
    <Drawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>

<script lang="tsx" setup>
  import { BasicTable, useTable, TableAction, ActionItem, FormSchema } from '@/components/Table';
  import { getRoleList, deleteRole } from '@/api/role';
  import { useDrawer } from '@/components/Drawer';
  import Drawer from './Drawer.vue';

  const columns: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 300,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '名称',
      component: 'Input',
      colProps: { span: 8 },
    },
  ];

  const [registerTable, { reload }] = useTable({
    title: '角色管理',
    api: getRoleList,
    columns,
    formConfig: {
      labelWidth: 60,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });

  const createActions = (record) => {
    const actions: ActionItem[] = [
      {
        label: '编辑',
        onClick: () => {
          handleEdit(record)
        },
      },
      {
        label: '删除',
        color: 'error',
        popConfirm: {
          title: '确认删除？',
          confirm: () => {
            handleDelete(record);
          },
        },
      },
    ];
    return actions;
  };

  const [registerDrawer, { openDrawer }] = useDrawer();

  function handleCreate() {
    openDrawer(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete(record: Recordable) {
    await deleteRole(record.id);
    reload();
  }

  function handleSuccess() {
    reload();
  }

</script>